﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BizWeb.Models.Interface;

namespace BizWeb.Models.Repository
{
    public class PostRepository : IPost
    {
        // Declare the data context for the repository
        private BizWebDataContext db = new BizWebDataContext();

        // Query Methods
        #region Query Methods
        public IQueryable<Site_Post> AllPosts()
        {
            return AllPosts(false);
        }

        public IQueryable<Site_Post> AllPosts(bool includeNonPublished)
        {
            if (includeNonPublished)
            {
                return db.Site_Posts.OrderByDescending(o => o.DatePublished);
            } else {
                return db.Site_Posts.Where(w => w.IsPublished == true).OrderByDescending(o => o.DatePublished);
            }
        }

        public IQueryable<Site_Post> RecentPosts(Int32 count)
        {
            // Shows the recent posts by date
            // return db.Site_Posts.Where(w => w.DatePublished >= DateTime.Now.AddDays(-days) && w.IsPublished == true).OrderByDescending(o => o.DatePublished);
            return db.Site_Posts.Where(w => w.IsPublished == true).OrderByDescending(o => o.DatePublished).Take(count);
        }

        public IQueryable<Site_Post> AllPostsForTag(string tag)
        {
            // TODO: Double check the following. Verify that the result set is filtered based on TagName
            //return db.Site_Posts.Where(w => w.Site_TaggedPosts.Where(p => p.Site_Tag.TagName == tag)).OrderByDescending(o => o.DatePublished);
            throw new NotImplementedException();
        }

        public IQueryable<Site_Post> AllPostsForTag(Guid id)
        {
            // TODO: Double check the following. Verify that the result set is filtered based on TagID
            //return db.Site_Posts.Where(w => w.Site_TaggedPosts.Where(p => p.TagID == id)).OrderByDescending(o => o.DatePublished);
            throw new NotImplementedException();
        }

        public Site_Post GetPost(Guid id)
        {
            return db.Site_Posts.Where(w => w.PostID == id).FirstOrDefault();
        }

        public Site_Post GetPost(DateTime date, String slug)
        {
            return db.Site_Posts.Where(w => w.Slug == slug && w.DateCreated.Date == date.Date).FirstOrDefault();
        }
        #endregion

        // 'Action' Methods
        #region "'Action' Methods"
        public void Add(Site_Post post)
        {
            db.Site_Posts.InsertOnSubmit(post);
        }

        public void Delete(Site_Post post)
        {
            db.Site_TaggedPosts.DeleteAllOnSubmit(post.Site_TaggedPosts);
            db.Site_Posts.DeleteOnSubmit(post);
        }

        public void Save()
        {
            db.SubmitChanges();
        }
        #endregion
    }
}